<template>
	<div class="user-box">
		<div class="fixed-header">
			<van-sticky>
				<div class="topdropdown">
					<van-dropdown-menu>
						<van-dropdown-item v-model="params.storesId" :options="option1" title="店铺"
							@change="storeChange" />
						<van-dropdown-item v-model="searchObj.value2" :options="option2" title="状态"
							@change="statusChange" />
					</van-dropdown-menu>
					<div class="dropdownLeft" v-if="params.storesId"></div>
					<div class="dropdownRight" v-if="searchObj.value2"></div>
				</div>
				<div class="searchBox">
					<van-search v-model="params.deviceName" :placeholder="placeholder" @search="handleSearch">
						<template #right-icon>
							<div class="search-confirm" @click.stop="handleSearch">
								<span style="margin-right: 10px;height: 24px;">|</span>
								<span class="search-text">搜索</span>
							</div>
						</template>
					</van-search>
				</div>
			</van-sticky>
		</div>
		<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
			<van-list v-model:loading="loading" v-model:error="error" error-text="请求失败，点击重新加载" finished-text="没有更多数据了"
				:finished="finished" @load="getdata">
				<DeviceList :list="list" :mark="mark" @RechargeHandle="reCharge"></DeviceList>
			</van-list>
		</van-pull-refresh>
	</div>
</template>

<script setup>
	import DeviceList from "@/components/deviceList.vue";
	const mark = ref('dataRecharge')
	const placeholder = ref('按设备号或店铺名称搜索')
	import {
		ref,
		onMounted,
		reactive
	} from "vue";
	import {
		getUserid
	} from '@/utils/auth';
	import {
		deviceEntityList,
		iccidLink
	} from "@/api/deviceEntity";
	import {
		StoresList
	} from "@/api/deviceRechargeConfig";
	import {
		showToast,
		showDialog
	} from 'vant';
	import {
		useRouter
	} from 'vue-router';
	const router = useRouter();

	onMounted(() => {
		getdata();
		getstore(); //店铺
	});

	const loading = ref(false);
	const finished = ref(false);
	const error = ref(false);
	// 下拉刷新状态
	const refreshing = ref(false);
	const params = ref({
		size: 10,
		pages: 1,
		userId: getUserid(),
		deviceName: '',
		storesId: '',
		deviceStatus: '',
	});
	const list = reactive([]);
	var option1 = reactive([]);


	const option2 = [{
		text: '全部',
		value: ''
	}, {
		text: '在线',
		value: 1
	}, {
		text: '离线',
		value: 2
	}];

	const searchObj = ref({
		value2: '',
	});
	//店铺
	const getstore = async () => {
		const userId = {
			userId: getUserid(),
		}
		try {
			const response = await StoresList(userId);
			const records = response.data || [];
			option1 = [{
				text: "全部",
				value: ''
			}, ...records.map((item) => ({ // 展开原数组
				text: item.storeName,
				value: item.id,
			}))];
		} catch (err) {
			//console.error('获取数据失败', err);
		}
	}

	const getdata = async (isRefresh = false) => {
		loading.value = false;
		try {
			// 防止重复请求
			if (loading.value && !isRefresh) return;
			// 重置错误状态
			error.value = false;
			// 设置加载状态
			loading.value = true;

			const response = await deviceEntityList(params.value);
			const records = response.data.records || [];
      // 新增：格式化时间
			const formattedRecords = records.map(item => ({
				...item,
				// 添加格式化后的时间字段（保留原始 createTime）
				createTime: formatISODate(item.createTime),
				bindTime: formatISODate(item.bindTime)
			}));

			// 如果是刷新操作，替换而不是追加数据
			if (isRefresh) {
				list.splice(0, list.length, ...formattedRecords);
			} else {
				list.push(...formattedRecords);
			}

			// 更新分页状态
			finished.value = records.length < params.value.size;
			params.value.pages += 1;
		} catch (err) {
			//console.error('获取数据失败', err);
			error.value = true;
			finished.value = false; // 确保可以重试

			// 如果是刷新操作需要保留刷新状态
			if (!isRefresh) {
				refreshing.value = false;
			}
		} finally {
			loading.value = false;
			// 如果是刷新操作，需要特殊处理
			if (isRefresh) {
				refreshing.value = false;
			}
		}
	};
	// 店铺切换
	const storeChange = () => {
		// 立即清空列表
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;

		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;

		// 直接调用 getdata，而不是等待列表自动触发
		getdata(true); // 传入 true 表示是刷新操作
	};
	// 状态切换
	const statusChange = (status) => {
		if (status) {
			params.value.deviceStatus = Number(status) - 1;
		} else {
			params.value.deviceStatus = '';
		}
		// 立即清空列表
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;

		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;

		// 直接调用 getdata，而不是等待列表自动触发
		getdata(true); // 传入 true 表示是刷新操作
	};
	// 下拉刷新处理
	const onRefresh = () => {
		// 立即清空列表
		list.splice(0, list.length);

		// 重置分页参数
		params.value.pages = 1;
		params.value.deviceName = '';
		params.value.storesId = '';
		params.value.deviceStatus = '';
		searchObj.value.value2 = '';

		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;

		// 直接调用 getdata，而不是等待列表自动触发
		getdata(true); // 传入 true 表示是刷新操作
	};
	// 输入框搜索
	const handleSearch = () => {
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;

		// 重置状态
		finished.value = false;
		loading.value = false;
		error.value = false;
		getdata(true);
	};
  // 流量充值
  const reCharge = async (item) => {
	if(item.iccid){
		const params = {
			iccid: item.iccid,
		}
		try {
			const response = await iccidLink(params);
			if (response.status == 200) {
				// 复制链接到剪贴板
				// navigator.clipboard.writeText(response.data);
				// 打开链接
				setTimeout(() => {
					window.open(response.data);
				}, 100);
			}else{
				showToast({
					type: 'fail',
					message: response.desc || '充值失败',
					forbidClick: true
				});
			}
		} catch (err) {
			showToast({
				type: 'fail',
				message: error.desc || '充值失败',
				forbidClick: true
			});
		}
	}else{
		showToast('无流量卡');
	}
  };
  // 时间格式化工具函数
	const formatISODate = (isoString) => {
		// 修复格式问题：将 "+0000" 转成 "+00:00"
		if (!isoString) return "-"; // 处理空值
		try {
			const fixedDateString = isoString.replace(/(\+\d{2})(\d{2})$/, "$1:$2");
			const date = new Date(fixedDateString);
			// 转为本地时间并格式化为 "YYYY-MM-DD HH:mm:ss"
			return date.toLocaleString("zh-CN", {
				year: "numeric",
				month: "2-digit",
				day: "2-digit",
				hour: "2-digit",
				minute: "2-digit",
				// second: "2-digit",
				hour12: false // 强制 24 小时制
			}).replace(/\//g, '-'); // 将斜杠替换为短横线（2025-02-23）
		} catch {
			return "-"; // 解析失败时返回占位符
		}
	};
</script>

<style scoped lang="scss">
	.topdropdown {
		position: relative;

		.dropdownLeft {
			position: absolute;
			bottom: 0;
			left: 16%;
			width: 20%;
			height: 3px;
			background-color: orange;
		}

		.dropdownRight {
			position: absolute;
			bottom: 0;
			right: 14%;
			width: 20%;
			height: 3px;
			background-color: orange;
		}
	}

	:deep(.van-dropdown-menu__bar) {
		box-shadow: none;

		.van-dropdown-menu__title {
			color: orange;
		}

		.van-dropdown-menu__title:after {
			border-color: transparent transparent orange orange;
		}
	}

	:deep(.searchBox) {
		.van-search {
			background-color: white;

			/* 搜索框 */
			.van-search__content {
				background-color: white;
				border: 1px solid #cccccc;
				/* border-radius: 5px; */
				background-color: #f5f5f5;
			}
		}

		.van-search__action {
			color: #fff;
			background-color: #2FBC3C;
			border-radius: 16px;
			width: 40px;
			text-align: center;
			margin: 0 10px;
		}

		/* 文字 */
		.search-confirm {
			display: flex;
			align-items: center;
			height: 100%;
			padding: 0 12px;

			.search-text {
				color: rgb(81, 164, 208);
				/* 蓝色搜索文字 */
				font-size: 14px;
				font-weight: 500;
				white-space: nowrap;
				cursor: pointer;
			}
		}
	}
</style>